#!/usr/bin/perl

use strict;
#no strict "refs";
use warnings;

use Getopt::Long;
use Config::IniFiles;
use Shell qw/touch date/;
use IO::File;
use Regexp::Common;

#use Smart::Comments;
my $VERSION="0.07";
my $configFile=undef;
my $dataFile=undef;
my $opt = GetOptions (
	"f|config=s" => \$configFile,    # string
	"d|data=s" => \$dataFile,
	);  # flag

unless ( defined ($configFile) and -f $configFile ) {
    print STDERR "Config file doesn't exists or is not defined !\n";
    exit 1;
}

unless ( defined ($dataFile) and -f $dataFile ) {
    print STDERR "Data file doesn't exists or is not defined !\n";
    exit 2;
}

my %ini;
tie %ini, 'Config::IniFiles', ( -file => $configFile );

my %pattern_matching_fields;

my $field_separator=$ini{'general'}{'separator'};
$field_separator='\|' if $field_separator eq "|";
### SEP : $field_separator

my $num_fields=$ini{'general'}{'numFields'};
### NUM FILED: $num_fields

my $error_filename=$dataFile.".".$ini{'general'}{'errfileext'};
my $zip_error_file=$ini{'general'}{'errzipped'};

my $zipped_file=1;
$zipped_file=undef unless $dataFile =~ /\.gz$/;

foreach my $section ( sort grep /Field/, keys %ini ) {
    ### SECTION : $section
    my $key = $section;
    $key=~ s/Field(\d+)$/$1/;
    my $value=$ini{$section}{'type'};
    ### KEY : $key
    ### VALUE : $value
    $pattern_matching_fields{$key}=$value;
}

### PATTERNS : %pattern_matching_fields;

my $data_handler=openFileHandle ( $dataFile, "<" ,$zipped_file );

unlink $error_filename if -f $error_filename;
my $error_handler=openFileHandle ( $error_filename, ">>", $zip_error_file );

my $num_li=1;
while (<$data_handler>) {
    s/\n$//g; 

    my $line=$_;
    ### NOUVELLLLLLLLLLLLLLLLLLLLLLLLLLLL
    ### LINE : $line
    my @elts=split /$field_separator/,$line, $num_fields;
    ### ELTS : @elts
    my $err=undef;
    for (my $i=0; $i<scalar(@elts);$i++) {
	### I : $i
	### ELT: $elts[$i]
	my $pattern=$pattern_matching_fields{$i+1};
	### PATTERN : $pattern
	#$pattern =~ s/\\/\\/g;
	unless ($elts[$i] =~ /^$pattern$/) {
		$err="$num_li;".($i+1).";$pattern;$line\n";
		print $error_handler $err;
		print $err;
		$err=undef;	
	} 
    }
    $num_li++;
} # END WHILE 

close($data_handler);
close($error_handler);

exit(0);

sub trim {
    my $string = shift;
    $string="" unless defined ($string);
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

sub openFileHandle {
    my $file= shift;
    my $dir= shift;
    my $zipped=shift;
    my $handle = new IO::File;
    if (defined $zipped and $zipped==1) {
	open ($handle, "| gzip $dir $file.gz"); #  we write to a pipe 
    } else {
	touch $file unless ( -f $file );
	die "$file : $@" unless ( -f $file );
	open($handle, "$dir $file") or die "$file: $!";
    }
    $handle->autoflush(1);
    ### FILE : $file
    ### HANDLER: $handle
    return $handle;
}
